//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Localization;
using System.Globalization;
namespace DotNetNuke.UI.WebControls
{
	[ToolboxData("<{0}:DateEditControl runat=server></{0}:DateEditControl>")]
	public class DateEditControl : EditControl
	{
		private TextBox dateField;
		private HyperLink linkCalendar;
		protected DateTime DateValue {
			get {
				DateTime dteValue = Null.NullDate;
				try 
                {
					string dteString = Value as string;
                    dteValue = DateTime.Parse(dteString, CultureInfo.InvariantCulture);
				} 
                catch (Exception ex) 
                {
				}
				return dteValue;
			}
		}
		protected virtual string DefaultFormat {
			get { return "d"; }
		}
		protected virtual string Format {
			get {
				string _Format = DefaultFormat;
				if (CustomAttributes != null) {
					foreach (System.Attribute attribute in CustomAttributes) {
						if (attribute is FormatAttribute) {
							FormatAttribute formatAtt = (FormatAttribute)attribute;
							_Format = formatAtt.Format;
							break;
						}
					}
				}
				return _Format;
			}
		}
		protected DateTime OldDateValue {
			get {
				DateTime dteValue = Null.NullDate;
				try 
                {
					string dteString = OldValue as string;
                    dteValue = DateTime.Parse(dteString, CultureInfo.InvariantCulture);
				} 
                catch (Exception ex)
                {
				}
				return dteValue;
			}
		}
		protected override string StringValue {
			get {
				string _StringValue = Null.NullString;
				if ((DateValue.ToUniversalTime().Date != DateTime.Parse("1754/01/01") && DateValue != Null.NullDate)) {
					_StringValue = DateValue.ToString(Format);
				}
				return _StringValue;
			}
			set { this.Value = DateTime.Parse(value); }
		}
		protected override void CreateChildControls()
		{
			base.CreateChildControls();
			dateField = new TextBox();
			dateField.ControlStyle.CopyFrom(this.ControlStyle);
			dateField.ID = this.ID + "date";
			Controls.Add(dateField);
			Controls.Add(new LiteralControl("&nbsp;"));
			linkCalendar = new HyperLink();
			linkCalendar.CssClass = "CommandButton";
			linkCalendar.Text = "<img src=\"" + DotNetNuke.Common.Globals.ApplicationPath + "/images/calendar.png\" border=\"0\" />&nbsp;&nbsp;" + Localization.GetString("Calendar");
			linkCalendar.NavigateUrl = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(dateField);
			Controls.Add(linkCalendar);
		}
		protected virtual void LoadDateControls()
		{
			if (DateValue != Null.NullDate) {
				dateField.Text = DateValue.Date.ToString("d");
			}
		}
		public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
		{
			this.EnsureChildControls();
			bool dataChanged = false;
            string presentValue = StringValue;
            string postedValue = postCollection[postDataKey + "date"];
            if(!presentValue.Equals(postedValue))
            {
                Value = DateTime.Parse(postedValue).ToString(CultureInfo.InvariantCulture);
                dataChanged = true;
            }

            return dataChanged;
		}
		protected override void OnDataChanged(EventArgs e)
		{
			PropertyEditorEventArgs args = new PropertyEditorEventArgs(Name);
			args.Value = DateValue;
			args.OldValue = OldDateValue;
            args.StringValue = DateValue.ToString(CultureInfo.InvariantCulture);
			base.OnValueChanged(args);
		}
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
			LoadDateControls();
			if (Page != null && this.EditMode == PropertyEditorMode.Edit) {
				this.Page.RegisterRequiresPostBack(this);
			}
		}
		protected override void RenderEditMode(HtmlTextWriter writer)
		{
			RenderChildren(writer);
		}
		protected override void RenderViewMode(System.Web.UI.HtmlTextWriter writer)
		{
			ControlStyle.AddAttributesToRender(writer);
			writer.RenderBeginTag(HtmlTextWriterTag.Span);
			writer.Write(StringValue);
			writer.RenderEndTag();
		}
	}
}
